//
//  LKNavBarTitleMenu.m
//  LKNovelty
//
//  Created by RoyLei on 16/11/16.
//  Copyright © 2016年 Laka. All rights reserved.
//

#import "LKNavBarTitleMenu.h"
#import "BNDOfficeDocKit.h"

@implementation BNDMenuModel

@end

NSInteger const LKTitleMenuDefaultCount = 4;

@interface LKNavBarTitleMenu()

@property (strong, nonatomic) NSMutableArray <BNDMenuModel *> *columns;

@property (strong, nonatomic) UIView *bottomView;

@property (strong, nonatomic) CALayer *maskLayer;
@property (strong, nonatomic) CAGradientLayer *gradientLayer;
@end

@implementation LKNavBarTitleMenu
@synthesize titles = _titles;

- (instancetype)initWithTitles:(NSArray *)titles
{
    self = [super initWithTitles:titles];
    if (self) {
        
        self.backgroundColor = [UIColor clearColor];
        self.clipsToBounds = NO;
        
        self.contentView.backgroundColor = [UIColor clearColor];
        self.contentView.clipsToBounds = NO;
    }
    return self;
}

- (void)setupGradientLayer
{
    if (!_maskLayer) {
        _maskLayer = [CALayer layer];
        _gradientLayer = [CAGradientLayer layer];
        [_maskLayer addSublayer:_gradientLayer];
        self.bottomView.layer.mask = _maskLayer;
        
        _maskLayer.frame = self.bottomView.bounds;
        _gradientLayer.frame = self.bottomView.bounds;
        
        id transparent = (__bridge id)[UIColor clearColor].CGColor;
        id opaque = (__bridge id)UIColorWithHex(0x000000).CGColor;
        CGFloat fadePercentage = 45.00/kDeviceWidth;
        
        _gradientLayer.colors = @[opaque, transparent];
        [_gradientLayer setStartPoint:CGPointMake(0, 0.5)];
        [_gradientLayer setEndPoint:CGPointMake(1, 0.5)];
        _gradientLayer.locations = @[@(1.0 - fadePercentage), @(1.0)];
    }
}

- (void)setButtonsAndSelfFrame
{
    __block CGRect butnRect = CGRectMake(5, 0, 0, self.height);
    __block CGFloat buttonWidth = 0;
    
    if (self.titles.count > 0 && self.titles.count <= LKTitleMenuDefaultCount) {
        butnRect.origin.x = 0;
        buttonWidth = ceilf((self.width - butnRect.origin.x * 2)/self.titles.count);
    }else {
        butnRect.origin.x = 15;
    }
    
    @weakify(self)
    [self.buttons enumerateObjectsUsingBlock:^(LSYTitleButton *butn, NSUInteger idx, BOOL *stop) {
        @strongify(self)
        [butn.titleLabel sizeToFit];
        
    
        buttonWidth = butn.titleLabel.width + 5;
        
        butnRect.size.width = buttonWidth;
        [butn setFrame:CGRectIntegral(butnRect)];
        butnRect.origin.x += butn.width + self.buttonMargin;
        
        if(self.menuStyle==1){
            butn.backgroundColor = UIColorWithHex(0xF5F8FF);
            butn.layer.cornerRadius =  butnRect.size.height/2;
            butn.layer.masksToBounds =  YES;
        }
       
        
    }];
    
    LSYTitleButton *lastButton = [self.buttons lastObject];
    
    [self.contentView setContentSize:CGSizeMake(CGRectGetMaxX(lastButton.frame) + 10, self.height)];
    
    self.sliderLine.centerX = self.selectButn.centerX;
}

- (CGSize)intrinsicContentSize
{
    LSYTitleButton *lastButton = [self.buttons lastObject];
    CGFloat containerWidth = MIN(self.containerMaxWidth, CGRectGetMaxX(lastButton.frame));
    return CGSizeMake(containerWidth, self.height);
}

- (void)setSelectedIndex:(NSUInteger)selectedIndex
{
    if (selectedIndex >= self.buttons.count) {
        return;
    }
    
    NSInteger lastIndex = self.selectedIndex;
    [self handleSelectedIndex:selectedIndex];

    @weakify(self)
    [self.buttons enumerateObjectsUsingBlock:^(LSYTitleButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        @strongify(self)
        if (idx == selectedIndex) {
            [obj setHighlighted:YES];
            [obj setSelected:YES];
            [obj.titleLabel setTextColor:self.titleSelectedColor];
            [obj.titleLabel setFont:self.titleSelectedFont];
            if(self.menuStyle==1){
            obj.backgroundColor = UIColorWithHex(0xF2F6FF);
            obj.layer.cornerRadius =  obj.size.height/2;
            obj.layer.masksToBounds =  YES;
            obj.layer.borderWidth =0.5;
            obj.layer.borderColor = UIColorWithHex(0x3770EB).CGColor;
            }
           
//            if (_scaleRate > 1.0) {
//                [obj.titleLabel setTransform:CGAffineTransformMakeScale(_scaleRate, _scaleRate)];
//            }
        }else {
            [obj setHighlighted:NO];
            [obj setSelected:NO];
            [obj.titleLabel setFont:self.titleNormalFont];
            [obj.titleLabel setTextColor:self.titleNormalColor];
            if(self.menuStyle==1){
            obj.backgroundColor = UIColorWithHex(0xF5F8FF);
            obj.layer.cornerRadius =  obj.size.height/2;
            obj.layer.masksToBounds =  YES;
            obj.layer.borderWidth =0.5;
            obj.layer.borderColor = UIColor.clearColor.CGColor;
            }
//            [obj.titleLabel setTransform:CGAffineTransformIdentity];
        }
    }];
    
    if (self.buttons.count > 3) {
        
        CGRect nextButtonFrame = self.selectButn.frame;
        
        nextButtonFrame = self.selectButn.frame;
        
        /*
         *如果上一次选中的index大于当前要切换的index,则滚动显示出当前要选择的index的前两个
         *否则滚动显示出显示当前要选择的index的后两个
         */
        if (lastIndex > selectedIndex) {

            if (selectedIndex <= 1) {
                nextButtonFrame = [self.buttons firstObject].frame;
            }else if(selectedIndex > 1) {
                nextButtonFrame = self.buttons[selectedIndex - 2].frame;
            }
            
        }else if (lastIndex < selectedIndex) {

            if (self.buttons.count <= selectedIndex + 2) {
                nextButtonFrame = [self.buttons lastObject].frame;
            }else if (self.buttons.count > selectedIndex + 2) {
                nextButtonFrame = self.buttons[selectedIndex + 2].frame;
            }
        }
        
        nextButtonFrame.origin.x -= 40;
        nextButtonFrame.size.width += 80;

        [self.contentView scrollRectToVisible:nextButtonFrame animated:YES];
    }
}

#pragma mark - Setter

- (void)setTitles:(NSMutableArray <NSString *> *)titles
{
    if (_titles != titles) {
        _titles = nil;
        _titles = titles;
        
        if (!_bottomView) {
            [self.contentView removeFromSuperview];
            [self.bottomView addSubview:self.contentView];
        }
        
        BOOL solButton = titles.count == 1 ? YES : NO;
        
        [self.buttons makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self.buttons removeAllObjects];
        
        __block CGFloat buttonWidth = 0;
        __block CGRect butnRect = CGRectMake(self.firstButtonLeftMargin, 0, 0, self.height);
        
        @weakify(self)
        [titles enumerateObjectsUsingBlock:^(NSString *title, NSUInteger idx, BOOL *stop) {
            @strongify(self)
            LSYTitleButton *butn = [self makeButtonWithTilte:title];
            butn.titleLabel.font = self.fontNormal;
            [butn setTag:idx];
            [butn setEnabled:solButton?NO:YES];
            
            [self.contentView addSubview:butn];
            [self.buttons addObject:butn];
            
            [butn.titleLabel sizeToFit];
            
            buttonWidth = [title boundingRectWithSize:(CGSize){320,30}
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{NSFontAttributeName : self.titleSelectedFont}
                                              context:nil].size.width + kDeviceRatio*4+20;
            
//            buttonWidth = buttonWidth;
            
            butnRect.size.width = buttonWidth;
            [butn setFrame:CGRectIntegral(butnRect)];
            butnRect.origin.x = CGRectGetMaxX(butnRect) + self.buttonMargin;
            if(self.menuStyle==1){
            butn.backgroundColor = UIColorWithHex(0xF5F8FF);
            butn.layer.cornerRadius =  butnRect.size.height/2;
            butn.layer.masksToBounds =  YES;
            }
            
            if (self.selectedIndex == idx) {
                [self.sliderLine setCenterX:butn.centerX];
            }
        }];
        
        if (titles.count) {
            [self setupContentSize];
        }
        [self setSelectedIndex:0];
    }
}

- (void)setupContentSize
{
    LSYTitleButton *lastButton = [self.buttons lastObject];
    
    if(CGRectGetMaxX(lastButton.frame) < kDeviceWidth) {
        
        self.contentView.bounces = NO;
        self.bottomView.layer.mask = nil;
        
        [self setWidth:CGRectGetMaxX(lastButton.frame)];
        
        [self.contentView setContentSize:CGSizeMake(CGRectGetMaxX(lastButton.frame), self.height)];
        
        [self.bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(CGRectGetMaxX(lastButton.frame));
        }];
        
        [self.contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self);
        }];
        
    }else {
        
        self.contentView.bounces = YES;
        
        [self setWidth:self.containerMaxWidth];
        
        [self.contentView setContentSize:CGSizeMake(CGRectGetMaxX(lastButton.frame) + 15, self.height)];
        
        [self.bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(self.containerMaxWidth);
         //   make.centerX.mas_equalTo(self.mas_centerX).offset((self.containerMaxWidth - kDeviceWidth)/2);
        }];
        
        [self.contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self.bottomView);
        }];
    }
    
    [self.contentView setContentOffset:CGPointZero];
    [self.contentView setNeedsLayout];
    [self.contentView layoutIfNeeded];
    
    [self setNeedsLayout];
    [self layoutIfNeeded];
    
    // 添加渐变遮罩图层
    if(CGRectGetMaxX(lastButton.frame) >= kDeviceWidth) {
        [self setupGradientLayer];
    }
}

#pragma mark - Helper Method

- (void)addedColumns:(NSArray <BNDMenuModel *> *)columns;
{
    [_columns addObjectsFromArray:columns];
    
    NSMutableArray *columnTitles = [NSMutableArray arrayWithCapacity:columns.count];
    for (BNDMenuModel *columnInfo in columns) {
        [columnTitles addObject:columnInfo.name];
    }
    
    [self addButtonsWithTitles:columnTitles];
}

// 如果有必要则更新导航栏目
- (void)updateNavBarTitleMenuTitlesIfneed:(NSArray <BNDMenuModel *> *)columns
{
    self.columns = [NSMutableArray arrayWithArray:columns];
    
    __block BOOL needUpdate = NO;
    
    if (!_titles || _titles.count == 0 || columns.count != _titles.count) {
        
        needUpdate = YES;
    }else {
        [self.titles enumerateObjectsUsingBlock:^(NSString *_Nonnull title, NSUInteger idx, BOOL * _Nonnull stop) {
            BNDMenuModel *columnInfo = columns[idx];
            if (![columnInfo.name isEqualToString:title]) {
                needUpdate = YES;
                *stop = YES;
            }
        }];
    }
    
    if (needUpdate) {
        NSMutableArray *columnTitles = [NSMutableArray arrayWithCapacity:columns.count];
        for (BNDMenuModel *columnInfo in columns) {
            [columnTitles addObject:columnInfo.name];
        }
        
        BND_dispatch_main_async_safe(^{
            [self setTitles:columnTitles];
            [self setNavBarTitleMenuPosition:columns];
        })
    }
}

#pragma mark - Show Or Hide NavBarTitleMenu

- (void)showTitleMenuView
{
    [self.sliderLine setHidden:NO];
    
    if (self.alpha >= 1.0f) {
        return;
    }
    [self setAlpha:1.0f];
}

- (void)hideTitleMenuView
{
    if (self.top < BNDNavigationBarHeight()) {
        return;
    }
    
    [UIView animateWithDuration:0.25 animations:^{
        [self setTop:0];
    } completion:^(BOOL finished) {
        [self setAlpha:0.0f];
    }];
}

- (void)setNavBarTitleMenuPosition:(NSArray<BNDMenuModel *> *)columns
{
    if (columns.count > 0) {
        [self setHidden:NO];
    }else {
        [self setHidden:YES];
    }
    
    NSUInteger currentIndex = self.selectedIndex;
    while (currentIndex >= columns.count) {
        currentIndex--;
    }
    [self setSelectedIndex:currentIndex];
    [self setSliderPosition];
    
    [self showTitleMenuView];
}

#pragma mark - Getter

- (UIView *)bottomView
{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:(CGRect){0, 0, kDeviceWidth, self.height}];
        [self addSubview:_bottomView];
        
        [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.mas_left);
            make.top.mas_equalTo(self.mas_top);
            make.bottom.mas_equalTo(self.mas_bottom);
            make.width.mas_equalTo(kDeviceWidth);
        }];
        
    }
    
    return _bottomView;
}

@end
